import cv2
import mediapipe as mp
import tkinter as tk
from PIL import Image, ImageTk
import controller
import pygame

def display_rules():
    rules = (
        "游戏规则：在不同的赛道，根据下落物摆出对应的手势来获得分数。\n"
        "        下落物下降速度和生成数量会随着获得的分数逐渐加快.\n"
        "        最多同时捕捉两只手."
    )
    root = tk.Tk()
    root.title("游戏规则")
    file = "./bgm/menu.mp3"
    pygame.mixer.init()
    track = pygame.mixer.music.load(file)
    root.geometry(f"{1280}x{720}+{50}+{50}")
    def destroy_window():
        cap.release()
        pygame.mixer.music.stop()
        root.destroy()

    canvas = tk.Canvas(root, width=1280, height=720)
    canvas.pack()

    back_photo = tk.PhotoImage(file="resource\\back.png")
    back_btn = tk.Button(root, image=back_photo,compound=tk.TOP, bg=root.cget('bg'), borderwidth=0)
    back_btn.place(x=0, y=0,width=100,height=50)

    custom_font = ("Helvetica", 24, "bold")
    label = tk.Button(root, text=rules,compound=tk.TOP, bg=root.cget('bg'), borderwidth=0,font=custom_font)
    label.place(x=180,y=0)
    cap = cv2.VideoCapture(0)

    def update_frame():
        with mp.solutions.hands.Hands(static_image_mode=False, max_num_hands=1, min_detection_confidence=0.5) as hands:
            success, image = cap.read()
            if not success:
                print("Ignoring empty camera frame.")
                root.after(10, update_frame)
                return

            image = cv2.flip(image, 1)
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            image = cv2.resize(image,(1280,720))
            results = hands.process(image)
            if results.multi_hand_landmarks:
                for hand_landmarks in results.multi_hand_landmarks:
                    index_finger_x = hand_landmarks.landmark[mp.solutions.hands.HandLandmark.INDEX_FINGER_TIP].x * \
                                     image.shape[1]
                    index_finger_y = hand_landmarks.landmark[mp.solutions.hands.HandLandmark.INDEX_FINGER_TIP].y * \
                                     image.shape[0]

                    if back_btn.winfo_x() < index_finger_x < back_btn.winfo_x()+back_btn.winfo_width() and \
                        back_btn.winfo_y() < index_finger_y < back_btn.winfo_y()+back_btn.winfo_height():
                        destroy_window()
                        controller.turn_to_menu()
                        return

            img = Image.fromarray(image)
            img = ImageTk.PhotoImage(image=img)
            canvas.create_image(0, 0, anchor=tk.NW, image=img)
            canvas.img = img
            root.after(10, update_frame)

    update_frame()
    pygame.mixer.music.play()
    root.mainloop()

if __name__ == '__main__':
    display_rules()
